package com.school.sports.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.school.sports.entity.SysDictType;
import com.school.sports.mapper.SysDictTypeMapper;
import com.school.sports.service.SysDictTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典类型服务实现类
 */
@Slf4j
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {

    @Autowired
    private SysDictTypeMapper sysDictTypeMapper;

    @Override
    public IPage<SysDictType> getDictTypePage(Integer currentPage, Integer pageSize, SysDictType sysDictType) {
        // 创建分页对象
        Page<SysDictType> page = new Page<>(currentPage, pageSize);

        // 构建查询条件
        QueryWrapper<SysDictType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        if (StringUtils.hasText(sysDictType.getDictName())) {
            queryWrapper.like("dict_name", sysDictType.getDictName());
        }
        if (StringUtils.hasText(sysDictType.getDictType())) {
            queryWrapper.like("dict_type", sysDictType.getDictType());
        }
        if (sysDictType.getStatus() != null) {
            queryWrapper.eq("status", sysDictType.getStatus());
        }

        // 按创建时间排序
        queryWrapper.orderByDesc("created_at");

        return this.page(page, queryWrapper);
    }

    @Override
    public SysDictType getDictTypeByType(String dictType) {
        return sysDictTypeMapper.selectByDictType(dictType);
    }

    @Override
    public boolean addDictType(SysDictType sysDictType, Long currentUserId) {
        // 检查字典类型是否已存在
        if (checkDictTypeExists(sysDictType.getDictType(), null)) {
            log.warn("字典类型已存在：{}", sysDictType.getDictType());
            return false;
        }

        // 设置默认值
        sysDictType.setCreatedAt(LocalDateTime.now());
        sysDictType.setUpdatedAt(LocalDateTime.now());
        sysDictType.setCreatedBy(currentUserId);
        sysDictType.setUpdatedBy(currentUserId);
        sysDictType.setDeleted(0);

        if (sysDictType.getStatus() == null) {
            sysDictType.setStatus(1); // 默认启用
        }

        return this.save(sysDictType);
    }

    @Override
    public boolean updateDictType(SysDictType sysDictType, Long currentUserId) {
        // 检查字典类型是否存在
        SysDictType existingDictType = this.getById(sysDictType.getId());
        if (existingDictType == null) {
            log.warn("字典类型不存在：{}", sysDictType.getId());
            return false;
        }

        // 检查字典类型是否已存在（排除当前字典类型）
        if (checkDictTypeExists(sysDictType.getDictType(), sysDictType.getId())) {
            log.warn("字典类型已存在：{}", sysDictType.getDictType());
            return false;
        }

        // 设置更新信息
        sysDictType.setUpdatedAt(LocalDateTime.now());
        sysDictType.setUpdatedBy(currentUserId);

        return this.updateById(sysDictType);
    }

    @Override
    public boolean deleteDictType(Long dictTypeId) {
        // 检查是否存在关联的字典数据
        // 这里可以添加检查逻辑，确保没有字典数据关联

        // 逻辑删除
        SysDictType dictType = new SysDictType();
        dictType.setId(dictTypeId);
        dictType.setDeleted(1);
        dictType.setUpdatedAt(LocalDateTime.now());
        return this.updateById(dictType);
    }

    @Override
    @Transactional
    public boolean batchDeleteDictTypes(List<Long> dictTypeIds) {
        // 检查是否存在关联的字典数据
        // 这里可以添加批量检查逻辑

        // 批量逻辑删除
        LocalDateTime now = LocalDateTime.now();
        List<SysDictType> updateDictTypes = dictTypeIds.stream()
                .map(dictTypeId -> {
                    SysDictType dictType = new SysDictType();
                    dictType.setId(dictTypeId);
                    dictType.setDeleted(1);
                    dictType.setUpdatedAt(now);
                    return dictType;
                })
                .collect(Collectors.toList());

        return this.updateBatchById(updateDictTypes);
    }

    @Override
    public boolean updateDictTypeStatus(Long dictTypeId, Integer status, Long currentUserId) {
        SysDictType dictType = new SysDictType();
        dictType.setId(dictTypeId);
        dictType.setStatus(status);
        dictType.setUpdatedAt(LocalDateTime.now());
        dictType.setUpdatedBy(currentUserId);

        return this.updateById(dictType);
    }

    @Override
    public boolean checkDictTypeExists(String dictType, Long excludeId) {
        return sysDictTypeMapper.countByDictType(dictType, excludeId) > 0;
    }

    @Override
    public List<SysDictType> getAllEnabledDictTypes() {
        return sysDictTypeMapper.selectAllEnabledDictTypes();
    }

    @Override
    public List<SysDictType> getDictTypesByName(String dictName) {
        return sysDictTypeMapper.selectByDictNameLike(dictName);
    }

    @Override
    public boolean refreshDictCache() {
        try {
            // 获取所有启用的字典类型和字典数据
            List<SysDictType> dictTypes = sysDictTypeMapper.selectAllEnabledDictTypes();

            // 这里可以添加缓存刷新逻辑，例如更新Redis缓存
            log.info("刷新字典缓存，共{}个字典类型", dictTypes.size());

            return true;
        } catch (Exception e) {
            log.error("刷新字典缓存失败", e);
            return false;
        }
    }
}